package com.itheima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.itheima.common.constants.SystemConstants;
import com.itheima.search.dto.SearchDto;
import com.itheima.search.mapper.ApUserSearchMapper;
import com.itheima.search.pojo.ApUserSearch;
import com.itheima.search.service.ApUserSearchService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @description <p>APP用户搜索信息 业务实现</p>
 *
 * @version 1.0
 * @package com.itheima.search.service.impl
 */
@Service
public class ApUserSearchServiceImpl extends ServiceImpl<ApUserSearchMapper, ApUserSearch> implements ApUserSearchService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 存入搜索记录到redis
     *
     * @param dto
     */

    @Override
    @Async(value = "redisExecutor")
    public void addSearchWords(SearchDto dto, Long userId) {
        String key = "USER_SEARCH::";
        if(userId == SystemConstants.ANONYMOUS_USER_ID){
            // 匿名 存入redis时使用设备id 为key
            key = key + dto.getEquipmentId();
        }else{
            // 登录用户 就使用用户id为key
            key = key + userId;
        }
        String searchWords = dto.getSearchWords();
        // list集合
        String jsonStringInRedis = stringRedisTemplate.opsForValue().get(key);
        List<String> list = new ArrayList<>(10);
        if(StringUtils.isNotEmpty(jsonStringInRedis)){
            list = JSON.parseArray(jsonStringInRedis, String.class);
            // 查询的字符串 是否已经存在redis中
            if(!CollectionUtils.isEmpty(list)) {
                if (list.contains(searchWords)) {
                    // 原来的list中已经有这个 搜索词
                    int index = list.indexOf(searchWords);
                    list.remove(index);
                }else if (list.size() >= 10) {
                    // 去掉最后一个 a
                    list.remove(9);
                }
            }
        }
        // 添加第一个
        list.add(0, searchWords);
        // 更新redis
        stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(list));
    }
}
